package br.com.serialmanager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.AppOpsManager.OnOpChangedListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import br.com.serialmanager.model.dao.SoftwareDao;
import br.com.serialmanager.webservice.HttpSoapRequest;

public class PrincipalActivity extends Activity implements Runnable {

	private Button btnNovoSoftware, btnListarSOftwares, btnSincronizarTodos;
	private ProgressDialog dialog;
	private SoftwareDao softwareDao;
	private Handler handler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.principal);
		
		this.softwareDao = new SoftwareDao(this);
		this.btnNovoSoftware = (Button) this.findViewById(R.id.novoSoftware);
		this.btnListarSOftwares = (Button) this.findViewById(R.id.listarSoftwares);
		this.btnSincronizarTodos = (Button) this.findViewById(R.id.sincronizar);
		
		this.handler = new Handler() {
			public void handleMessage(Message msg) {
				updateUI(msg);
			}
		};
	}
	
	private void updateUI(Message message) {
		if (message.what > 0) {
			Toast.makeText(this, R.string.dados_sincronizados, Toast.LENGTH_SHORT).show();
		} else if (message.what == 0 || message.what == -2) {
			Toast.makeText(this, R.string.sem_dados_para_sincronizar, Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, R.string.erro_sincronizar, Toast.LENGTH_SHORT).show();
		}
	}
	
	public void selecionarOpcao(View view) {
		int id = view.getId();
		Intent intent = new Intent();
		switch (id) {
			case R.id.novoSoftware:
				intent.setClass(this, NovoSoftwareActivity.class);
				this.startActivity(intent);
				break;
			case R.id.listarSoftwares:
				intent.setClass(this, ListaSoftwareActivity.class);
				this.startActivity(intent);
				break;
			case R.id.sincronizar:
				this.dialog = ProgressDialog.show(this, null, getString(R.string.sincronizando_registros), true);
				new Thread(this).start();
				break;
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		this.sincronizarRegistros();
	}
	
	private void sincronizarRegistros() {
		HttpSoapRequest soapRequest = new HttpSoapRequest("server.smanager", "http://www.rodrigootacilio.com.br/ws/server.php", "sincronizarSoftwares");
		Message message = new Message();
		try {
			if (this.preparaDados() != null) {
				soapRequest.addProperty("listaSoftwares", this.preparaDados());
				soapRequest.makeRequest();
				Object resp = soapRequest.getResponse();
				message.what = Integer.valueOf(resp.toString());
			} else {
				message.what = -2;
			}
			this.handler.sendMessage(message);
			this.dialog.dismiss();
		} catch (Exception e) {
			Log.e("ERROR", e.getMessage());
			this.dialog.dismiss();
		}
	}

	private String preparaDados() {
		// TODO Auto-generated method stub
		StringBuilder saida = new StringBuilder();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		List<Map<String, Object>> softwares = this.softwareDao.listarSoftwares();
		List<String> items = new ArrayList<String>();
		if (!softwares.isEmpty()) {
			for (int i = 0; i < softwares.size(); i++) {
				saida.append("[");
				saida.append(softwares.get(i).get("soft_id")).append(":");
				saida.append(softwares.get(i).get("nome_software")).append(":");
				if (softwares.get(i).get("data_validade") != null) {
					saida.append(formatter.format(softwares.get(i).get("data_validade"))).append(":");
				} else {
					saida.append("").append(":");
				}
				saida.append(softwares.get(i).get("numero_de_serie")).append(":");
				saida.append(softwares.get(i).get("masc_formato"));
				saida.append("]");
				items.add(saida.toString());
				saida = new StringBuilder();
			}
			String retorno = "";
			int lastIndex = items.size() - 1;
			for (String s : items) {
				if (s.equals(items.get(lastIndex))) {
					retorno += s;
				} else {
					retorno += s + ",";
				}
			}
			return retorno;
		}
		return null;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = this.getMenuInflater();
		inflater.inflate(R.menu.menu_action_bar, menu);
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getItemId() == R.id.novaMascara) {
			Intent intent = new Intent(this, NovaMascaraActivity.class);
			this.startActivity(intent);
		}
		return super.onMenuItemSelected(featureId, item);
	}
}
